import { RbacMenuBtnType } from '@/data/auth/menu';
import { useMenus } from '@/hooks/auth/useMenus';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { ProFormGroup } from '@ant-design/pro-form/lib';
import React, { useEffect, useRef } from 'react';

const AddForm: React.FC<{
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: RbacMenuBtnType) => Promise<void>;
  values?: Partial<any>;
}> = ({ visible, onCancel, onSubmit, values }) => {
  const { allMenuValueEnum } = useMenus();
  const formRef = useRef<any>(null);

  useEffect(() => {
    if (formRef.current && visible) {
      formRef.current.resetFields();
    }
  }, [values, visible]);


  const getModalFormKey = () => {
    if (values && values.id) {
      return values?.id || Math.random();
    } else {
      return Math.random();
    }
  };

  return (
    <ModalForm
      title="新建"
      width="800px"
      open={visible}
      onFinish={onSubmit}
      formRef={formRef}
      onOpenChange={(value) => {
        if (!value) onCancel();
      }}
      key={`menu-add-button-form-${getModalFormKey()}`}
    >
      <ProFormGroup colProps={{ span: 12 }}>
        <ProFormSelect
          width="md"
          name="menuId"
          label={'菜单'}
          valueEnum={allMenuValueEnum}
          disabled={true}
          initialValue={values?.menuId}
        />

        <ProFormText
          rules={[
            {
              required: true,
              message: '按钮名称为必填项',
            },
            {
              pattern: /^[\u4e00-\u9fa50-9]+$/,
              message: '只能输入中文字符',
            },
          ]}
          width="md"
          name="name"
          label={'按钮名称'}
          placeholder={'请输入按钮名称'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '按钮标识为必填项',
            },
            {
              pattern: /^[a-zA-Z0-9:]+$/,
              message: '只能输入英文字符',
            },
          ]}
          width="md"
          name="btnPerm"
          label={'按钮标识'}
          initialValue={values?.name}
          placeholder={'请输入按钮标识'}
        />
      </ProFormGroup>
    </ModalForm>
  );
};

export default AddForm;
